package com.shop.mall.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Freemarker模板配置
 *
 * @author admin
 * @version 1.0
 * @date 2019/4/23
 */
@WebServlet(name = "freemarker")
public class FreemarkerConfig extends HttpServlet {
    private static final long serialVersionUID = -1914005012281853922L;
    private Configuration configuration;

    @Override
    public void init() {
        System.out.println("执行freemarker init()");
        // 初始化Freemarker配置
        configuration = new Configuration(Configuration.VERSION_2_3_28);
        // 设置Freemarker模板文件的位置
        configuration.setServletContextForTemplateLoading(this.getServletContext(), "templates");
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行freemarker doPost()");
        // 数据
        Map root = new HashMap();
        root.put("user", "Jack");

        // 获取模板
        Template t = configuration.getTemplate("Test.ftl");

        // 准备输出， 使用模板的编码作为本页的charset
        response.setContentType("text/html; charset=" + t.getEncoding());
        PrintWriter out = response.getWriter();

        try {
            // 在模板中加入动态数据
            t.process(root, out);
        } catch (TemplateException e) {
            throw new ServletException("处理Template模版中出现错误", e);
        }
    }
}
